package com.carpool.message;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.google.android.maps.GeoPoint;

public class ReverseGeocode {
	private static final String BASE_URL = "http://maps.google.com/maps/api/geocode/xml?";

	// static String urlString =
	// "http://maps.google.com/maps/api/geocode/xml?latlng=30.509310,120.681100&sensor=false";
	public static String parseCoords(GeoPoint point) {
		String address = null;

		StringBuilder urlString = new StringBuilder();
		urlString.append(BASE_URL).append("latlng=")
				.append(point.getLatitudeE6() / 1E6).append(",")
				.append(point.getLongitudeE6() / 1E6).append("&sensor=false");
		try {
			URL url = new URL(urlString.toString());
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setRequestMethod("GET");
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.connect();
			address = parseString(connection.getInputStream());
		} catch (Exception e) {
			address = null;
		}
		return address;
	}

	private static String parseString(InputStream inputStream) throws Exception {
		String address=null;
	
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document document = builder.parse(inputStream);
		Element root = document.getDocumentElement();// root data
		NodeList list = root.getChildNodes();
		for (int i = 0; i < list.getLength(); i++) {
			Node node = list.item(i);
			if (node.getNodeType() == Node.ELEMENT_NODE) {
				if (node.getNodeName().equals("result")) {
					NodeList slist = node.getChildNodes();
					for (int j = 0; j < slist.getLength(); j++) {
						Node snode = slist.item(j);
						if (snode.getNodeType() == Node.ELEMENT_NODE) {

							if ("formatted_address".equals(snode.getNodeName())) {
								address=snode.getFirstChild().getNodeValue();
								return address;
							}
						}
					}
				}
			}
		}

			
		return null;
	}
}
